<template>
  <scroll-view
        style="height: 100%;"
        :refresher-triggered="isToRefresh"
        scroll-y
        :refresher-enabled="true"
        @refresherpulling="isToRefresh = true"
        @refresherrefresh="onScrollTop"
        refresher-default-style="none"
        refresher-background="#ededed"
        @scrolltolower="scrolltolower"
  >
      <view v-if="isToRefresh" class="pull-down-refresh" >
        <image :src="$imgUrl('/uploading.gif')" mode="heightFix" class="refresh-indicator"></image>
      </view>
      <main class="main">
      <view class="container">
        <swiper
            class="swiper-wrapper"
            circular
            :indicator-dots="false"
            :autoplay="autoplay"
            :interval="interval"
            :duration="duration"
            @change="swiperChange"
            @touchstart="onTouchStart"
            @touchmove="onTouchMove"
            @touchend="onTouchEnd"
        >
          <swiper-item v-for="(item, index) in images.slice(0,6)" :key="index">
            <view class="banner-swiper-wrapper"
            >
<!--              <image :style="{height: '1200rpx', width: '100%'}" :src="item.src">-->
              <image :style="{height: '1200rpx', width: '100%'}"
                     :src="`https://ifashion-mini.oss-cn-shanghai.aliyuncs.com/images/goods_${index + 1}.png`"
              >
              </image>
              <view>
                <view class="banner-wrapper-text">
                  <text> {{  advers.goods_name|| 'World’s Best Cloth Collection' }}</text>
                </view>
                <view class="little-text">
                  <text> {{ advers.name   || 'Discover Product' }} </text>
                </view>
              </view>
            </view>
          </swiper-item>
        </swiper>
        <view class="banner-text-wrapper" :style="`padding-top: ${$customTop}px`">
          <view class="banner-top">
            <view class="left-box">
              <image style="width: 48rpx;height: 48rpx;margin-right:40rpx;pointer-events: auto;" :src="$imgUrl('/search.png')" mode="widthFix" @click="$navTo('pages/search/index')"></image>
              <image style="width: 275rpx;" :src="$imgUrl('/logo.png')" mode="widthFix"></image>
            </view>
            <view class="right-box">
              <image style="pointer-events: auto;" :src="$imgUrl('/bag.png')" class="bag_icon" @click="$navTo('pages/cart/index')"></image>
              <view style="pointer-events: auto;" v-if="isLogin" class="avatar" @click="$navTo('pages/user/index')">
                <avatar-image :url="userInfo.avatar_url" width="80" height="80" />
              </view>
              <!-- 未登录 -->
              <view v-else class="user-info" style="pointer-events: auto;" @click="$navTo('pages/user/index')">
                <view class="avatar">
                  <avatar-image width="80" height="80" />
                </view>
              </view>
            </view>
          </view>
          <view class="indicator-wrapper">
            <view class="indicator-item" :style="`width: ${360 / images.length}rpx;transform: translateX(${100 * (currentIndex)}%)`"></view>
          </view>
        </view>
      </view>
<!--    具体产品系列-->
      <view class="goods-container">
        <text class="goods-title-name">{{ recoms[0]?.name }} </text>
        <view class="more-name-title" @click="handleGoods(recoms[0]?.category_id, recoms[0]?.name)">
        <text class="more-name">更多产品</text>
        <image  style="width: 24rpx;height: 48rpx;" :src="$imgUrl('/white_back_arrow.png')"></image>
        </view>
      </view>
      <view class="goods-collect" >
        <view class="shopping-card" v-for="(product, index) in products.slice(0,10)" :key="index">
        <image
            class="card-image"
            :src="product.goods_image "
            @click="onTargetGoods(product.goods_id)"
          ></image>
        <view class="card-decoration">
          <image
              class="heart-image"
              :src="product.isHeartFilled ? filledHeartImage : emptyHeartImage"
              @click="toggleHeart(index)"
          ></image>
        </view>
        <view class="card-info">
          <text class="card-title">{{ product.goods_name }}</text>
          <text v-if="product.goods_price_max" class="card-price">￥{{ product.goods_price_max }}</text>
        </view>
      </view>
      </view>
      <view class="goods-container" style="margin-top: 34rpx;margin-bottom:34rpx;">
      <text class="goods-title-name">往季推荐</text>
      <view class="more-name-title" @click="navigateToMorePage">
      <text class="more-name">更多</text>
      <image  style="width: 24rpx;height: 48rpx;" :src="$imgUrl('/white_back_arrow.png')"></image>
      </view>
    </view>
      <view class="recom-card" >
        <view class="recom-shopping-card"
              v-for="(recom, index) in recoms.slice(0,6)" :key="index"
              @click="handleGoods(recom.category_id, recom.name)"
        >
          <view class="recom-card-left">
            <image
                class="producted-image"
                :src="recom.src || `https://ifashion-mini.oss-cn-shanghai.aliyuncs.com/images/goods_${index + 1}.png`"
                mode="aspectFill"></image>
          </view>
          <view class="recom-card-right">
            <view class="recom-card-right-decoration">
              <text class="producted-title">{{ recom.name }}</text>
              <text class="producted-link" >SHOP NOW</text>
            </view>
          </view>
      </view>
    </view>
      </main>
    </scroll-view>
</template>

<script>
  import Page from '@/components/page'
  import PrivacyPopup from '@/components/privacy-popup'
  import Images from "../../components/page/diyComponents/image/index.vue";
  import VkUviewUi from "../../uni_modules/vk-uview-ui/components/vk-uview-ui/vk-uview-ui.vue";
  import * as  CategoryApi from '@/api/category';
  import * as GoodsApi from "@/api/goods";
  import * as UserApi from '@/api/user';
  import * as SwiperImgApi from '@/api/swiperImg'
  import AvatarImage from '@/components/avatar-image'
  import { checkLogin } from '@/core/app';


  const App = getApp()
  export default {
    components: {
      VkUviewUi,
      Images,
      Page,
      PrivacyPopup,
      AvatarImage,
    },
    data() {
      return {
        // 当前用户信息
        userInfo: {},
        // 是否已登录
        isLogin: false,
        images: [
          { src: 'https://ifashion-mini.oss-cn-shanghai.aliyuncs.com/images/page1.jpg' },
          { src: 'https://ifashion-mini.oss-cn-shanghai.aliyuncs.com/images/page1.jpg' },
        ],
        autoplay: true,
        interval: 2500,
        duration: 500,
        currentIndex: 0,
        swipeWidth: 360, // 滑块宽度
        startX: 0, // 触摸开始时的位置
        touchStartTimestamp: null, // 触摸开始的时间戳
        touchEndTimestamp: null, // 触摸结束的时间戳
        isDragging: false, // 是否正在拖动
        emptyHeartImage: 'https://ifashion-mini.oss-cn-shanghai.aliyuncs.com/images/heart.png',
        filledHeartImage: 'https://ifashion-mini.oss-cn-shanghai.aliyuncs.com/images/heartfill.png',
        //下拉刷新样式
        isToRefresh: false,
        recoms:[],
        products: [],
        advers:[],
        goods:{},
        name: '',
        firstCategoryId: null,
      }
    },
    async onLoad() {
      await this.getCategoryList()
      await this.getGoodsList()
      await this.getUserInfo()
      await this.getSwiperList()
    },
    methods: {
      // 获取当前用户信息
      getUserInfo() {
        const app = this
        // 判断是否已登录
        app.isLogin = checkLogin()
        return new Promise((resolve, reject) => {
          !app.isLogin ? resolve(null) : UserApi.info({})
              .then(result => {
                app.userInfo = result.data.userInfo
                resolve(app.userInfo)
              })
              .catch(err => {
                if (err.result && err.result.status == 401) {
                  app.isLogin = false
                  resolve(null)
                } else {
                  reject(err)
                }
              })
        })
      },
      async getCategoryList() {
        try {
          const response = await CategoryApi.list();
          if (response.status === 200) {
            this.recoms = response.data.list;
            this.name = response.data.list.name;
            // 获取第一个系列的的数据
            this.firstCategoryId = this.recoms[0]?.category_id;
          } else {
            uni.showToast({
              title: '获取数据失败',
              icon: 'none',
              duration: 1500
            });
          }
        } catch (error) {
          console.error('Error fetching data:', error);
          uni.showToast({
            title: '网络错误',
            icon: 'none',
          });
        }
      },
      async getGoodsList() {
        try {
          const categoryId = this.firstCategoryId  ;
          const response = await GoodsApi.list({ categoryId, page: 1 }, { load: false });
          if (response.status === 200) {
            this.products = response.data.list.data;
          } else {
            uni.showToast({
              title: '获取数据失败',
              icon: 'none',
              duration: 1500
            });
          }
        } catch (error) {
          console.error('Error fetching data:', error);
          uni.showToast({
            title: '网络错误',
            icon: 'none',
          });
        }
      },
      async getSwiperList() {
        try {
          const response = await SwiperImgApi.index();
          if (response.status === 200) {
            this.advers= response.data;
          } else {
            uni.showToast({
              title: '获取数据失败',
              icon: 'none',
              duration: 1500
            });
          }
        } catch (error) {
          console.error('Error fetching data:', error);
          uni.showToast({
            title: '网络错误',
            icon: 'none',
          });
        }
      },
      async onScrollTop() {
        this.isToRefresh = true
        await this.getCategoryList()
        this.isToRefresh = false
      },
      swiperChange(e) {
        this.currentIndex = e.detail.current;
      },
      toggleHeart(index) {
        this.products[index].isHeartFilled = !this.products[index].isHeartFilled;
      },
      onTouchStart(e) {
        this.startX = e.touches[0].clientX;
        this.touchStartTimestamp = Date.now();
        this.isDragging = true;
        clearInterval(this.timer); // 清除定时器，暂停自动轮播
      },
      onTouchMove(e) {
        if (!this.isDragging) return;
        const moveX = e.touches[0].clientX;
        const diffX = this.startX - moveX;
      // 根据移动方向控制滑动
      if (Math.abs(diffX) > 50) {
      if (diffX > 0) {
      // 向左滑动，切换到上一张
          this.swiperChange({ detail: { current: (this.currentSlide - 1 + this.images.length) % this.images.length } });
        } else {
          // 向右滑动，切换到下一张
          this.swiperChange({ detail: { current: (this.currentSlide + 1) % this.images.length } });
        }
       }
      },
      onTouchEnd(e) {
        this.isDragging = false;
        this.touchEndTimestamp = Date.now();
        const touchDuration = this.touchEndTimestamp - this.touchStartTimestamp;

        // 只有短暂的触摸才视为点击
        if (touchDuration < 200) {
          // 点击行为
        }
        // 恢复自动轮播
        this.timer = setInterval(() => {
          this.swiperChange({ detail: { current: (this.currentSlide + 1) % this.images.length } });
        }, this.interval);
      },
      navigateToMoreGoods() {
        uni.navigateTo({
          url: '/pages/recom-list/goods-list',
        });
      },
      navigateToMorePage() {
        uni.navigateTo({
          url: '/pages/recom-list/index',
        });
      },
      // 跳转至商品列表页
      handleGoods(categoryId, categoryName) {
        this.$navTo('pages/recom-list/goods-list', { categoryId, categoryName})
      },
      onTargetGoods(goodsId) {
        this.$navTo('pages/goods/detail',{ goodsId })
      },
      goToPage(url) {
        uni.navigateTo({ url })
      },
      //   滚动到页面底部
      scrolltolower() {
      },
  },
}

</script>

<style lang="scss" scoped>
  //下拉刷新样式
  .pull-down-refresh {
    position: relative;
    height: 144rpx;
    background-color: #ededed; // 灰色背景
    display: flex;
    align-items: center;
    justify-content: center;
    // margin-top: -45px;
  }
  .refresh-indicator {
		//height: 288rpx;
    // width: 88rpx;
     height: 88rpx;
  }
	.main {
		background: #000;
		height: 100%;
		width: 100vw;
	}
	.banner-top {
		height: 250rpx;
		//width: 100%;
		display: flex;
		align-items: center;
		padding: 0 40rpx;
		justify-content: space-between;
	}
  .container {
    overflow: hidden;
    position: relative;
    background: #fff;
    width: 750rpx;
  }
  .swiper-wrapper {
    position: relative;
    height: 1200rpx;
  }

  .mask-container {
    position: relative;
    width: 100%;
    height: 100%;
  }

  .swiper-item-image {
    width: 100%;
    height: 100%;
  }
  .banner-swiper-wrapper {
    position: relative;
  }
  .banner-wrapper-text{
    position: absolute;
    left: 40rpx;
    bottom: 164rpx;
    //width: 244px;
    height: 240rpx;
    opacity: 1;
    font-family: Satoshi;
    font-size: 100rpx;
    font-weight: bold;
    line-height: 80%;
    letter-spacing: 0em;
    color: #FFFFFF;
  }
  .little-text{
    position: absolute;
    left: 40rpx;
    bottom: 102rpx;
    height: 36rpx;
    opacity: 1;
    margin-top: 26rpx;
    font-family: Helvetica Neue;
    font-size: 36rpx;
    font-weight: normal;
    line-height: 36rpx;
    letter-spacing: 0em;
    color: #FFFFFF;
  }
  .banner-text-wrapper {
    position: absolute;
    left: 0rpx;
    top: 0rpx;
    width: 750rpx;
    height: 1200rpx;
		pointer-events: none;
  }
  .indicator-wrapper {
    width: 360rpx;
    height: 2rpx;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin: 20rpx 40rpx;
    background: rgba(216, 216, 216, 0.4);
    transition: transform 0.3s ease;
    position: absolute;
    bottom: 20rpx;

  }
  .indicator-item {
    height: 2rpx;
    background: rgba(216, 216, 216, 1);
  }
  .mask {
    position: absolute;
    left: 0px;
    top: 0px;
    width: 750rpx;
    height: 1200rpx;
    //opacity: 1;
    background: linear-gradient(360deg, rgba(0, 0, 0, 0.8) 0%, rgba(84, 84, 84, 0) 99%);
  }
  .avatar {
    width: 80rpx;
    height: 80rpx;
    border-radius: 50%;
    overflow: hidden;
    border: 4rpx solid rgba(255, 255, 255, 0.6);
    box-sizing: content-box;
  }
  .left-box,
  .right-box {
    display: flex;
    align-items: center;
  }
	.bag_icon {
		width: 48rpx;
		height: 48rpx;
		margin-right: 40rpx;
	}
	.message-img {
		position: absolute;
    display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 40rpx;
		bottom: 164rpx;
		width: 488rpx;
		opacity: 1;
		font-family: Satoshi;
		font-size: 100rpx;
		font-weight: bold;
		line-height: 80%;
		letter-spacing: 0em;
		font-variation-settings: "opsz" auto;
		color: #FFFFFF;
	}
	.message-bottom{
		position: absolute;
		display: flex;
    align-items: center;
    justify-content: space-between;
    padding: 0 40rpx;
		bottom: 102rpx;
		height: 36rpx;
		opacity: 1;
		font-family: Helvetica Neue;
		font-size: 36rpx;
		font-weight: normal;
		line-height: 36rpx;
		letter-spacing: 0em;
		color: #FFFFFF;
	}
  .goods-container{
    //height: 250rpx;
    margin-top: 129rpx;
    display: flex;
    align-items: center;
    padding: 0 40rpx;
    justify-content: space-between;
  }
  .goods-title-name{
    position: static;
    display: flex;
    align-items: center;
    justify-content: space-between;
    opacity: 1;
    font-family: Satoshi;
    font-size: 40rpx;
    font-weight: normal;
    line-height: 60rpx;
    letter-spacing: 0em;
    color: #FFFFFF;
    z-index: 0;
  }
  .more-name-title{
    position: static;
    display: flex;
    align-items: center;
  }
  .more-name{
    position: static;
    display: flex;
    align-items: center;
    justify-content: space-between;
    margin-right: 4rpx;
    opacity: 1;
    /* Headline — 15pt */
    font-family: DM Sans;
    font-size: 30rpx;
    //font-weight: bold;
    line-height: 30rpx;
    text-align: right;
    letter-spacing: 0em;
    color: #FFFFFF;
    z-index: 0;
  }
  .goods-collect{
    display: flex;
    padding: 0 40rpx;
    margin-top: 49rpx;
    flex-wrap: wrap;
    justify-content: space-between;
    /* align-items: center; */
    width: 100%;
  }
  .shopping-card {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    //margin-right:20rpx;
    //width: 100%;
    max-width: 326rpx;
    margin-bottom: 60rpx;
  }

  .card-image {
    width: 326rpx;
    height: 434rpx;
    margin-bottom: 20rpx;
  }
  .card-decoration {
    position: absolute;
    top: 16rpx;
    right: 16rpx;
    width: 72rpx;
    height: 72rpx;
    border-radius: 50%;
    background-color: #fff;
    overflow: hidden;
    display: flex;
    justify-content: center;
    align-items: center;
  }
  .heart-image {
    width: 36rpx;
    height: 32rpx;

  }

  .card-info {
    display: flex;
    flex-direction: column;
    width: 100%;
  }

  .card-title {
    font-size: 28rpx;
    font-weight: bold;
    margin-bottom: 10rpx;
    color: #FFFFFF;
    //font-family: Satoshi;
    line-height: 38rpx;

  }
  .card-price {
    font-family: Satoshi;
    font-size: 28rpx;
    color: #FFFFFF;
  }
.recom-card{
  padding-bottom: 150rpx;
}
  .recom-shopping-card {
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 40rpx;
    padding-bottom: 20rpx;
  }

  .recom-card-left, .recom-card-right {
    width: 335rpx;
    height: 446rpx;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
  }

  .recom-card-right {
    background-color: #fff;
    text-align: center;
  }
  .recom-card-right-decoration{
    display: flex;
    flex-direction:column;
  }

  .producted-image {
    width: 100%; /* 图片宽度充满容器 */
    height: 100%; /* 图片高度充满容器 */
    object-fit: cover; /* 保持图片比例填充容器 */
  }

  .producted-title {
    margin-bottom: 40rpx; /* 与下方内容间隔 */
    /* 自动布局子元素 */
    width: 295rpx;
    opacity: 1;
    text-align: left;
    font-family: Satoshi;
    font-size: 40rpx;
    font-weight: bold;
    line-height: 54rpx;
    letter-spacing: 0em;
  }

  .producted-link {
    position: relative;
    width: fit-content;
    opacity: 0.9;
    text-align: left;
    font-family: Source Han Sans CN;
    font-size: 28rpx;
    font-weight: 400;
    line-height: 42rpx;
    color: #000000;
    z-index: 0;
  }
  .producted-link::after {
  	content: '';
  	position: absolute;
  	bottom: 2rpx;
  	left: 0;
  	width: 100%;
  	height: 2rpx;
  	background: #000000;
  }



</style>
